<?php
namespace App\Http\Controllers\admin_system;

use App\Common\ApiData;
use App\Http\Controllers\Weixin\WeixinServiceController;
use App\Models\V1\ChangeOrderTemplateModel;
use App\Models\V1\ChapterModel;
use App\Http\Controllers\Controller;
use App\Models\V1\CompanyModel;
use App\Models\V1\DrpModel;
use App\Models\V1\MemberModel;
use App\Models\V1\ReadPartyModel;
use App\Modules\EntMemberInfo;
use Illuminate\Http\Request;
use DB;
use App\Common\MobileMassege;
use SimpleSoftwareIO\QrCode\BaconQrCodeGenerator;
use Illuminate\Support\Facades\Crypt;


class ChapterOrderController extends Controller{

    private $prisidentPercent = 60;

    /**
     * 分会订单列表
     * */
    public function orders(Request $request){
        $chapterId      = $request->input('chapterId',0);
        $keywords       = $request->input('keywords','');
        $orderStatus    = $request->input('orderStatus','-1');
        $chapterModel   = new ChapterModel();
        $orders         = $chapterModel->get_all_chapter_orders($chapterId,$orderStatus,$keywords);

        return view('admin_system/chapter/orders',['orders'=>$orders]);
    }


    /**
     * 订单详细界面
     * */
    public function order_detail(Request $request){
        $orderId        = $request->input('orderId');
        $chapterModel   = new ChapterModel();
        $orderInfo      = $chapterModel->get_order_info($orderId);

        $memberModel    = new MemberModel();
        $orderOwnerInfo = $memberModel->get_member_info_by_id($orderInfo->user_id);

        $orderInfo->user_name   = $orderOwnerInfo->YourName;
        $orderInfo->user_mobile = $orderOwnerInfo->UserName;

        $orderTypes = [
            'clo'       => '学习官',
            'member'    => '个人会员',
            'company'   => '企业会员',
            'prisident' => '会长'
        ];
        $orderInfo->order_type_name = $orderTypes[$orderInfo->order_type];

        //1.受益人-学习官
        $drpModel   = new DrpModel();
        $drpUserId  = $orderInfo->user_id;
        $handInfo   = $chapterModel->get_order_check_info($orderId,$drpUserId);
        $drpHandInfo= $handInfo ? $handInfo : new \stdClass();
        $drpHandInfo->isHand    = $handInfo ? 1 : 0;
        $drpHandInfo->YourName  = $orderOwnerInfo->YourName;
        $drpHandInfo->incomeMoney   = $orderInfo->pay_money * 0.3;
        $parentDrps = $drpModel->get_parent_drp_list($drpUserId,1);
        $parentNum  = count($parentDrps);

        //2.受益人-父级学习官
        $parentDrpHandInfo  = false;
        $mishuHandInfo      = false;

        if($parentNum >= 1) {

            $parentDrp   = $parentDrps[0];
            $userId     = $parentDrp->UserID;
            $handInfo   = $chapterModel->get_order_check_info($orderId,$userId);
            $parentDrpHandInfo          = $handInfo ? $handInfo : new \stdClass();
            $parentDrpHandInfo->isHand  = $handInfo ? 1 : 0;
            $parentDrpHandInfo->YourName= $parentDrp->YourName;
            $parentDrpHandInfo->incomeMoney = $orderInfo->pay_money * 0.1;

        } else {
                $mishuId    = system_log('mishuId');
                $handInfo = $chapterModel->get_order_check_info($orderId,$mishuId);
                if($handInfo)
                {
                    $mishuHandInfo = $handInfo;
                    $mishuHandInfo->isHand = 1;

                } else {

                    $mishuHandInfo          = new \stdClass();
                    $mishuHandInfo->isHand  = 0;
                }
                $mishuHandInfo->YourName = "小秘书";
                $mishuHandInfo->incomeMoney = $orderInfo->pay_money * 0.1;
                $mishuHandInfo->percent = 10;
        }

        //3.受益人-父2级学习官
        $topDrpHandInfo = false;

        //4.会长是否处理
        $memberInfo = $drpModel->get_member_info_by_id($orderInfo->check_user_id);
        $handInfo   = $chapterModel->get_order_check_info($orderId,$orderInfo->check_user_id);
        $prisidentHandInfo          = $handInfo ? $handInfo : new \stdClass();
        $prisidentHandInfo->isHand  = $handInfo ? 1 : 0;
        $prisidentHandInfo->YourName= $memberInfo->YourName;
        $prisidentHandInfo->incomePercent   = $this->prisidentPercent;
        $prisidentHandInfo->incomeMoney     = $orderInfo->pay_money * ($this->prisidentPercent / 100);


        $handInfo   = [
            'prisidentHandInfo' => $prisidentHandInfo,
            'drpHandInfo'       => $drpHandInfo,
            'parentDrpHandInfo' => $parentDrpHandInfo,
            'topDrpHandInfo'    => $topDrpHandInfo,
            'mishuHandInfo'     => $mishuHandInfo
        ];

        $data   = ['orderInfo'=>$orderInfo,'handInfo'=>$handInfo];
        return view('admin_system/chapter/order-detail',$data);
    }



    /*
     * 处理订单
     * */
    public function handle_order(Request $request){

        $orderId    = $request->input('orderId');
        $checkResult= $request->input('checkResult');
        $checkMsg   = $request->input('checkMsg');
        $memberEndDate  = date("Y-m-d",strtotime("+1 year"));   //截止时间

        $apiData        = new ApiData();
        $chapterModel   = new ChapterModel();

        $memberModel    = new MemberModel();
        $orderInfo      = $chapterModel->get_order_info($orderId);

        $orderUserId    = $orderInfo->user_id;
        $orderOwnerInfo = $memberModel->get_member_info_by_id($orderUserId);


        if($orderInfo->company_check_status > 0)
        {
            return $apiData->send(4000,'本订单已受理，请勿重复提交');
        }


        /*=========================未通过审核 begin =========================*/

        if($checkResult == 0)
        {
            return $this->check_order_fail($orderInfo,$orderOwnerInfo,$checkMsg);
        }

        /*=========================未通过审核 end =========================*/



        /*=========================审核通过 begin ==========================*/

        $drpModel       = new DrpModel();
        $chapterId      = $orderInfo->chapter_id;
        $parentDrpInfo  = $drpModel->get_drp_info_by_user_id($orderInfo->user_id);
        $orderType      = $orderInfo->order_type;


        if($orderType == 'member' ) //添加个人会员
        {
            //检查系统是否存在该用户
            $oldMemberInfo = $memberModel->get_member_info_by_mobile($orderInfo->new_member_mobile);

            //注意：这里仅仅考虑的是一个还未激活的用户 实际上有可能该用户已经是会员了，只是延长时间而已

            if($oldMemberInfo != false) //存在用户 则激活该用户 并且产生关联
            {
                $newMemberInfo = [
                    'UserID'            => $oldMemberInfo->UserID,
                    'States'            => 1,
                    'personal_end_time' => $memberEndDate,
                    'MemEndTime'        => $memberEndDate
                ];
                $memberModel->update_member_info($newMemberInfo);
                $memberNumber = $oldMemberInfo->MemNumber;
                $userId       = $oldMemberInfo->UserID;
                TableLog()
                    ->table('memberinfo')
                    ->key($oldMemberInfo->UserID)
                    ->content($newMemberInfo)
                    ->note('审核报单成功，激活用户，订单ID'.$orderId)
                    ->save();

            } else {    //用户不存在，创建一个新的用户

                $newUserInfo    = [
                    'States'    => 1,
                    'UserName'  => $orderInfo->new_member_mobile,
                    'YourName'  => $orderInfo->new_member_name,
                    'NickName'  => $orderInfo->new_member_name,
                    'city'      => $orderInfo->city,
                    'MemEndTime'=> $memberEndDate,
                    'personal_end_time' => $memberEndDate,
                    'RegisterType'      => "学习官推荐",
                ];

                $memberModel    = new MemberModel();
                $userId         = $memberModel->register($newUserInfo);
                $memberInfo     = $memberModel->get_member_info_by_id($userId);
                $memberNumber   = $memberInfo->MemNumber;

                TableLog()
                    ->table('memberinfo')
                    ->key($userId)
                    ->content($newUserInfo)
                    ->note('报单审核成功，添加会员')
                    ->save();
            }

            //关联学习官
            $drpInfo    = $drpModel->get_drp_info_by_member_number($memberNumber);

            if(!$drpInfo){
                $drpModel->add_drp_child($memberNumber,$parentDrpInfo->DRPID);
                TableLog()
                    ->table('memberdrp')
                    ->content(['MemNumber'=>$memberNumber,'ParentID'=>$parentDrpInfo->DRPID])
                    ->note("将会员与学习官关联")
                    ->save();
            }

            //关联分会
            $chapterModel->add_chapter_member($orderInfo->chapter_id,$userId);
            //通知新会员，告诉其已经成为新会员

            TableLog()
                ->table('chapter_member')
                ->content(['chapter_id'=> $chapterId,'user_id'=>$userId])
                ->note("将会员加入到分会下面")
                ->save();

        }
        elseif($orderType == 'clo') //添加学习官
        {
            //1在成为学习官之前，该用户必须是一个会员
            $newMobile      = $orderInfo->new_member_mobile;
            $newMemberInfo = $memberModel->get_member_info_by_mobile($newMobile);
            if(!$newMemberInfo || $newMemberInfo->States == 0) //不存在 || 未激活
            {
                return  $apiData->send(4001,"新提交的学习官还没有成为激活的会员");
            }

            $cloInfo    = $drpModel->get_drp_info_by_user_id($orderInfo->user_id);
            $drpModel->add_drp_child($newMemberInfo->MemNumber,$cloInfo->DRPID,true);

            //创建二维码
            $drpInfo= $drpModel->get_member_drp_info($newMemberInfo->UserID);
            $url    = 'http://wx.laohoulundao.com/parent/' . $drpInfo->DRPID . '.html';
            $imgPath= public_path('/uploads/qrcode/' . $drpInfo->MemNumber . '.png');
            $qrcode = new BaconQrCodeGenerator;
            $qrcode->format('png')->size(300)->generate($url, $imgPath);

            TableLog()
                ->table('memberdrp')
                ->content(['ParentID'=>$cloInfo->DRPID,'MemNumber'=>$newMemberInfo->MemNumber])
                ->note('关联会员和学习官')
                ->save();

            //关联分会  学习官所属区域永远跟着父亲走
            $chapterDrpInfo = DB::table('chapter_drp')->where('user_id',$orderInfo->user_id)->where('is_delete',0)->first();
            $chapterModel->add_chapter_officer($chapterDrpInfo->chapter_id,$newMemberInfo->UserID,$orderInfo->total_money);
            TableLog()
                ->table('chapter_drp')
                ->note('关系学习官和分会')
                ->content(['chapter_id'=>$chapterDrpInfo->chapter_id,'user_id'=>$newMemberInfo->UserID,'total_money'=>$orderInfo->total_money])
                ->save();
        }
        elseif($orderType == 'company') //添加企业会员
        {
            $companyModel   = new CompanyModel();
            $packageInfo    = $companyModel->get_company_package_info($orderInfo->company_package_id);

            $companyInfo    = [
                "vip_end_date"      => $memberEndDate,
                "vip_port"          => $packageInfo->port_number,
            ];
            if($orderInfo->is_upgrade == 1)
            {
                $companyId                  = $orderInfo->content_id;
                $companyInfo['company_id']  = $companyId;
                $companyModel->update_company($companyInfo);

            }else{

                $companyInfo['company_name']    = $orderInfo->new_company_name;
                $companyInfo['vip_begin_date']  = current_date();
                $companyInfo['city']            = $orderInfo->city;
                $companyInfo['drp_user_id']     = $orderInfo->user_id;
                $companyId                      = $companyModel->add_company($companyInfo);
            }


            $companyInfo2   = $companyModel->get_company_info($companyId);
            $companySn      = $companyInfo2->company_sn;
            TableLog()
                ->table('company')
                ->note('订单审核成功')
                ->content($companyInfo)
                ->key($companyId)
                ->save();

            //关联分会
            if($orderInfo->content_id == 0)
            {
                $chapterModel->add_chapter_company($orderInfo->chapter_id,$companyId);
                TableLog()
                    ->table('chapter_company')
                    ->note('订单审核成功关联新公司到分会')
                    ->content(['chapter_id'=>$chapterId,'company_id'=>$companyId])
                    ->save();

                if(false) //自动创建读书会  暂时不用
                {
                    //自动创建一个读书会
                    $companyName    = $orderInfo->new_company_name;
                    $readPartyData = [
                        'States'      => 1,
                        'Tel'         => "",
                        'ReaParType'  => 1,
                        'Regulation'  => "",
                        'ReaParName'  => $companyName,
                        'MemNumber'   => '',
                        'company_id'  => $companyId,
                        'companyname' => $companyName,
                        'CreaterName' => "",
                    ];
                    $readPartyModel = new ReadPartyModel();
                    $readPartyId = $readPartyModel->add_read_party($readPartyData);
                    //创建一个未分组的部门
                    $department = [
                        'company_id'    => $companyId,
                        'read_party_id' => $readPartyId,
                        'department_name'=>'未分组'
                    ];
                    $companyModel->update_department($department);


                    //1.添加一个系统默认账户
                    $data   = [
                        'name'          => $orderInfo->new_member_mobile,
                        'password'      => bcrypt($companyInfo2->company_sn),
                        'company_code'  => $companySn,
                        'company_name'  => $companyInfo2->company_name,
                        'created_at'    => date_time(),
                        'updated_at'    => date_time(),
                        'pid'           => 1
                    ];
                    DB::connection('mysql_2')->table('admin_users')->insert($data);
                }
            }


        }


        //1如果有从会长那里购买 则扣除会长的余额
        $payMoney   = $orderInfo->pay_money;
        if($payMoney > 0)
        {
            $prisidentUserId    = $orderInfo->check_user_id;
            $chapterModel->use_prisident_money($prisidentUserId,$orderInfo->pay_money);
            DrpModel::out_money_log($prisidentUserId,$orderInfo->pay_money,$orderId,"xxx");
            TableLog()
                ->table('chapter_prisident')
                ->content(['user_id'=>$prisidentUserId,'order_id'=>$orderId,'money'=>$orderInfo->pay_money])
                ->note('订单确认扣款')
                ->save();

            //将分配金额记录到学习官的收益数据中
            //1.学习官
            $money  = $payMoney * 0.3;
            $sql    = " UPDATE  chapter_drp
                        SET     total_sales = total_sales + $money
                        WHERE   user_id   = $orderUserId
                        AND     is_delete = 0 ";
            DB::update($sql);

            //2.会长
            $money  = $payMoney * 0.6;
            $sql = "UPDATE chapter_prisident
                    SET total_sales   = total_sales + $money
                    WHERE chapter_id  = $orderInfo->chapter_id
                    AND   user_id     = $prisidentUserId
                    AND   is_delete   = 0 ";
            DB::update($sql);

            //3.父学习官
            $incommers   = $orderInfo->income_member;
            $incommers   = explode(',',$incommers);

            foreach($incommers as $singleCommer)
            {
                if($singleCommer != $orderUserId && $singleCommer != $prisidentUserId)
                {
                    $money  = $payMoney * 0.1;
                    $sql    = " UPDATE  chapter_drp
                        SET     total_sales = total_sales + $money
                        WHERE   user_id   = $singleCommer
                        AND     is_delete = 0 ";
                    DB::update($sql);
                }
            }
        }

        $data = [
            'company_check_status'  => $checkResult,
            'company_check_msg'     => $checkMsg
        ];
        $chapterModel->update_chapter_order($orderId,$data);
        TableLog()
            ->table('chapter_order')
            ->key($orderId)
            ->content($data)
            ->note('订单审核成功')
            ->save();


        //更改返点记录的完成状态
        DB::table('pushmoneylog')->where('order_id',$orderId)->update(['IsFinish'=>1]);


        //如果是公司  初始化企业后台登录用户
        $messageModel           = new MobileMassege();


        //给相关人员短信通知
        switch($orderType)
        {
            case 'member':
                $mobileMsg  = "亲爱的{$orderInfo->new_member_name}，欢迎加入教导读书会。点击http://dwz.cn/6zgAMe下载教导读书会APP，登录即可享受会员服务，账户为您的手机号，获取验证码登录。";
                break;
            case 'clo':
                $mobileMsg  = "亲爱的{$orderInfo->new_member_name}，欢迎加入教导读书会。您的学习官身份已开通，在布道的路上我们相伴同行。";
                break;
            case 'company':
                //$mobileMsg  = "您好，{$orderInfo->new_company_name}的企业读书会账号已经开通！请使用编码：{$companySn},密码：{$companySn}，手机：{$orderInfo->new_member_mobile}登录http:://qiye.jdclo.com 登录管理社群";
                $mobileMsg  = "您好，{$orderInfo->new_company_name}的企业读书会账号已经开通！请使用编码：{$companySn}在教导读书会APP创建社群";
                //给学习官发送信息
                $messageModel->mobile = $orderOwnerInfo->UserName;
                $messageModel->send_msg($mobileMsg);
                break;
        }

        $messageModel->mobile   = $orderInfo->new_member_mobile;
        $messageModel->send_msg($mobileMsg);


        //订单提示
        $this->notice_result_to_clo($orderInfo,$orderOwnerInfo);

        //给孙颖发送一个新增学习官的通知
        if($orderType == 'clo')
        {
            $this->notice_clo_to_sunyin($orderInfo->new_member_name,$orderInfo->chapter_order_id);
        }
        return $apiData->send(200,"已审核,已将新的成员加入系统中");
    }


    /**
     * 给订单所属学习官发送提示
     * @param Object $orderInfo 订单信息
     * @param Object $orderOwnerInfo 学习官信息
     * */
    private function notice_result_to_clo($orderInfo,$orderOwnerInfo)
    {
        if(!$orderOwnerInfo->WeiXID)
        {
            return ;
        }
        $memberName             = $orderInfo->order_type == 'company' ? $orderInfo->new_company_name : $orderInfo->new_member_name;
        $template               = new ChangeOrderTemplateModel();
        $template->orderSn      = $orderInfo->chapter_order_id;
        $template->openId       = $orderOwnerInfo->WeiXID;
        $template->url          = env('ADMIN_HOST')."/clo/system/wxlogin";
        $template->orderInfo    = "您在{$orderInfo->add_time}提交的申请{$memberName}为新的{$orderInfo->order_type_name}";
        $template->changeInfo   = "总部受理了本订单，审核通过";
        $template->title        = "订单审核通知";
        $template->otherInfo    = "点击查看";
        $weixinservice          = new WeixinServiceController();
        $weixinservice->send_chapter_order_change_template($template);
    }

    /**
     * 新增学习官给孙颖一个通知
     * @param string $memberName clo名字
     * @param integer $orderId 订单编号
     * */
    private function notice_clo_to_sunyin($memberName,$orderId)
    {
        $openId                 = "oPF8hxIQ6l_DBk_wHqbdjqDSmA30";
        $template               = new ChangeOrderTemplateModel();
        $template->orderSn      = $orderId;
        $template->openId       = $openId;
        $template->url          = env('ADMIN_HOST')."/clo/system/wxlogin";
        $template->orderInfo    = "新增一名学习官【{$memberName}】";
        $template->changeInfo   ="总部受理了本订单，审核通过";
        $template->title        = "订单审核通知";
        $template->otherInfo    = "点击查看";
        $weixinservice          = new WeixinServiceController();
        $weixinservice->send_chapter_order_change_template($template);
    }



    /**
     * 审核订单失败
     * @param Object $orderInfo 订单信息
     * @param Object $orderOwnerInfo 订单用户信息
     * @param string $checkMsg 审核信息
     * @return Apidata
     * */
    private function check_order_fail($orderInfo,$orderOwnerInfo,$checkMsg)
    {
        //返回学习官被扣除的余点
        $checkResult    = 2;
        //如果是新购 则退换的金额应该是  已经支付的=总的-向分会支付的
        if($orderInfo->is_upgrade ==0)
        {
            $returnMoney    = $orderInfo->total_money - $orderInfo->pay_money;
        }
        else    //如果是升级  则退换的金额应该是 已经支付的 = 总的 - 向分会支付的 - 上次套餐抵扣的
        {
            $companyModel   = new CompanyModel();
            $oldPackageMoney= $companyModel->get_company_upgrade_discount($orderInfo->content_id,$orderInfo->add_time);
            $returnMoney    = $orderInfo->total_money - $orderInfo->pay_money - $oldPackageMoney;
        }

        $chapterModel       = new ChapterModel();

        if($returnMoney>0)
        {
            $chapterModel->return_officer_money($orderInfo->user_id,$returnMoney);
            TableLog()
                ->table('chapter_drp')
                ->key($orderInfo->user_id)
                ->content("返金额".$returnMoney)
                ->note('订单审核失败，返钱给学习官')
                ->save();
        }

        $updateInfo = ['company_check_status'=>$checkResult,'company_check_msg'=>$checkMsg];
        $chapterModel->update_chapter_order($orderInfo->chapter_order_id,$updateInfo);

        TableLog()
            ->table('chapter_order')
            ->key($orderInfo->chapter_order_id)
            ->content($updateInfo)
            ->note('审核报单失败')
            ->save();

        //订单提示
        if($orderOwnerInfo->WeiXID) //订单提示
        {
            $template           = new ChangeOrderTemplateModel();
            $template->orderSn  = $orderInfo->chapter_order_id;
            $template->openId   = $orderOwnerInfo->WeiXID;
            $template->url      = env('ADMIN_HOST')."/clo/system/wxlogin";
            $template->orderInfo= "您在{$orderInfo->add_time}提交的订单";
            $template->changeInfo="总部对本订单进行了审核，但审核失败，原因是:{$checkMsg}";
            $template->title    = "订单审核通知";
            $template->otherInfo = "点击查看";
            $weixinservice      = new WeixinServiceController();
            $weixinservice->send_chapter_order_change_template($template);
        }
        return apiData()->send(200,"已审核,{$returnMoney}订单金额已返给学习官");
    }

    /**
     * 企业套餐升级
     * 需要做的工作包含
     * 1.扣除会长的金额
     * 2.修改分配记录为已完成
     * 3.给相关受益人添加分享金额
     * */
    public function upgrade_company(Request $request)
    {
        $orderId    = $request->input('orderId');
        $checkResult= $request->input('checkResult');
        $checkMsg   = $request->input('checkMsg');

        $apiData        = new ApiData();
        $chapterModel   = new ChapterModel();

        $memberModel    = new MemberModel();
        $orderInfo      = $chapterModel->get_order_info($orderId);
        $companyId      = $orderInfo->content_id;

        $weixinservice  = new WeixinServiceController();
        $orderUserId    = $orderInfo->user_id;
        $orderOwnerInfo = $memberModel->get_member_info_by_id($orderUserId);

        $memberEndDate  = date("Y-m-d",strtotime("+1 year"));   //截止时间

        $companyModel   = new CompanyModel();
        $packageInfo    = $companyModel->get_company_package_info($orderInfo->company_package_id);


        $companyInfo    = [
            "vip_end_date"      => $memberEndDate,
            "vip_port"          => $packageInfo->port_number,
            "company_id"        => $companyId
        ];

        $companyModel->update_company($companyInfo);
        $companyInfo    = $companyModel->get_company_info($companyId);


        TableLog()
            ->table('company')
            ->note('订单审核成功升级企业会员')
            ->content($companyInfo)
            ->key($companyId)
            ->save();


        //1如果有从会长那里购买 则扣除会长的余额
        if($orderInfo->pay_money > 0)
        {
            $prisidentUserId    = $orderInfo->check_user_id;
            $chapterModel->use_prisident_money($prisidentUserId,$orderInfo->pay_money);
            DrpModel::out_money_log($prisidentUserId,$orderInfo->pay_money,$orderId,"");
            TableLog()
                ->table('chapter_prisident')
                ->content(['user_id'=>$prisidentUserId,'order_id'=>$orderId,'money'=>$orderInfo->pay_money])
                ->note('订单确认扣款')
                ->save();
        }

        $data = [
            'company_check_status'  => $checkResult,
            'company_check_msg'     => $checkMsg
        ];
        $chapterModel->update_chapter_order($orderId,$data);
        TableLog()
            ->table('chapter_order')
            ->key($orderId)
            ->content($data)
            ->note('订单审核成功')
            ->save();


        //更改返点记录的完成状态
        DB::table('pushmoneylog')->where('order_id',$orderId)->update(['IsFinish'=>1]);

        //给相关人员短信通知

        $mobileMsg  = "亲，{$orderInfo->new_company_name}的升级已完成！";
        $mobile     = $orderOwnerInfo->UserName;

        $messageModel           = new MobileMassege();
        $messageModel->mobile   = $mobile;
        $messageModel->send_msg($mobileMsg);

        if($orderOwnerInfo->WeiXID) //订单提示
        {
            $template           = new ChangeOrderTemplateModel();
            $template->orderSn  = $orderInfo->chapter_order_id;
            $template->openId   = $orderOwnerInfo->WeiXID;
            $template->url      = env('ADMIN_HOST')."/clo/system/wxlogin";
            $template->orderInfo= "您在{$orderInfo->add_time}提交的订单总部客服对其进行了审核";
            $template->changeInfo="总部受理了本订单，审核通过";
            $template->title    = "订单审核通知";
            $template->otherInfo = "点击查看";
            $weixinservice->send_chapter_order_change_template($template);
        }
        return $apiData->send(200,"已审核,已将新的成员加入系统中");
    }

    //阿里支付测试
    public function alipay(){

        include app_path("Libs/AliPay/AopSdk.php");

        $payConfig  = config('aliyun');
        $aliPay     = $payConfig['AliPay'];
        $aop = new \AopClient ();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = '2017082508377723';
        //$aop->rsaPrivateKey = '请填写开发者私钥去头去尾去回车，一行字符串';
        $aop->rsaPrivateKey = $aliPay['rsaPrivateKey'];
        //$aop->alipayrsaPublicKey='请填写支付宝公钥，一行字符串';
        $aop->alipayrsaPublicKey=$aliPay['alipayPublicKey'];
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='UTF-8';
        $aop->format='json';
        $request = new \AlipayFundTransToaccountTransferRequest ();
        $request->setBizContent("{" .
            "\"out_biz_no\":\"3142321423432\"," .
            "\"payee_type\":\"ALIPAY_LOGONID\"," .
            "\"payee_account\":\"zhweixi@sina.cn\"," .
            "\"amount\":\"0.01\"," .
            "\"payer_show_name\":\"教导读书会返点\"," .
            "\"payee_real_name\":\"\"," .
            "\"remark\":\"返点\"" .
            "  }");
        $result = $aop->execute ( $request);

        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if(!empty($resultCode)&&$resultCode == 10000){
            echo "成功";
        } else {
            echo "失败";
        }
    }


    /**
     * 删除订单
     * */
    public function order_delete(Request $request)
    {
        $orderId    = $request->input('orderId',0);
        $chapterModel   = new ChapterModel();

        if($orderId <= 0)
        {
            return apiData()->notice('订单ID错误');
        }

        //订单必须进行审核才能删除，以防扣了学习官的余额而没有退还
        $orderInfo  = $chapterModel->get_order_info($orderId);
        if($orderInfo->check_status == 0)
        {
            return apiData()->notice('订单必须先审核，才能删除');
        }

        DB::table('chapter_order')->where('chapter_order_id',$orderId)->update(['is_delete'=>1]);
        return apiData()->notice('删除成功');
    }
    
}
